﻿/// <reference path="vswd-ext_2.2.js" />


var myChooseDeviceListRowSSSID = "";
var xg = Ext.grid;
var devicestore;
Ext.chart.Chart.CHART_URL = 'Scripts/component/resources/charts.swf';
Ext.ns('DeviceList');
DeviceList.version = 'Beta 2';

var devicereader = new Ext.data.JsonReader({}, [{
				name : 'sssid'
			}, {
				name : 'alarminfo'
			}, {
				name : 'alarmcustomText'
			}, {
				name : 'choosed',
				type : 'boolean'
			}, {
				name : 'trackername'
			}, {
				name : 'lastupdate'
			}, {
				name : 'process'
			}, {
				name : 'retry'
			}, {
				name : 'username'
			}, {
				name : 'actionalarm',
				type : 'string'
			}, {
				name : 'qtipalarm',
				type : 'string'
			}, {
				name : 'actionretry'
			}, {
				name : 'qtipretry'
			}, {
				name : 'commandid',
				type : 'int'
			}, {
				name : 'parameters'
			}, {
				name : 'devicetype',
				type : 'int'
			}, {
				name : 'latitude',
				type : 'float'
			}, {
				name : 'longitude',
				type : 'float'
			}, {
				name : 'alarmtime'
			}, {
				name : 'alarmexp'
			}, {
				name : 'status'
			}, {
				name : 'online',
				type : 'boolean'
			}, {
				name : 'atype',
				type : 'boolean'
			}, {
				name : 'routename'
			}, {
				name : 'routedata'
			}, {
				name : 'alarmspeed',
				type : 'float'
			}, {
				name : 'alarmlatitude',
				type : 'float'
			}, {
				name : 'alarmlongitude',
				type : 'float'
			}, {
				name : 'journey',
				type : 'int'
			}, {
				name : 'basemileage',
				type : 'int'
			}, {
				name : 'servicedue',
				type : 'int'
			}
			//   { name: 'lastgeofenceid', type: 'int' },
		, {
				name : 'lastgeofencename',
				type : 'string'
			}, {
				name : 'distance',
				type : 'int'
			}, {
				name : 'direction'
			},
			 {
				name : 'iconname'
			}
		
		]);

var chkDeviceSelection = new Ext.grid.CheckColumn({
		header : '',
		width : 25,
		sortable : false,
		id:'xxxxx',
		dataIndex : 'choosed',
		listeners: {
            checkchange: function (column, recordIndex, checked) {
                alert(checked);
                
            }
        }
	});

var proxy = new Ext.data.HttpProxy({
		url : 'HandlerDeviceList',
		timeout : 90000
	});

devicestore = new Ext.data.GroupingStore({
		autoSave : true,
		reader : devicereader,
		proxy : proxy,
		sortInfo : {
			field : 'username',
			direction : "ASC"
		},
		groupField : 'username'
	});

function isInputAlarm(alarmexp) {
	if (alarmexp == _AlarmResource_SOSButton_Pressed_Input1_Active || alarmexp == _AlarmResource_SOSButton_Released_Input1_InActive
		 || alarmexp == _AlarmResource_ButtonB_Pressed_Input2_Active || alarmexp == _AlarmResource_ButtonB_Released_Input2_InActive
		 || alarmexp == _AlarmResource_ButtonC_Pressed_Input3_Active || alarmexp == _AlarmResource_ButtonC_Released_Input3_InActive
		 || alarmexp == _AlarmResource_Input4_Active || alarmexp == _AlarmResource_Input4_InActive
		 || alarmexp == _AlarmResource_Input5_Active || alarmexp == _AlarmResource_Input5_InActive) {
		return true;
	} else
		return false;
}

devicestore.addListener('load', function (store, records) {
	var i;
	for (i = 0; i < records.length; i++) {
		var record = records[i];

		var alarmstring = record.get("qtipalarm");
		var servicedue = record.get("servicedue");
		var journey = record.get("journey");
		if (servicedue > 0 && servicedue < journey) {
			var win = serviceDueWindow(record.get("sssid"), record.get("trackername"), journey / 1000, servicedue);
			nextwindowx += 20;
			nextwindowy += 20;
			win.show(); // 显示出来
		}
		record.set("servicedue", servicedue / 1000);
		if (alarmstring.length > 0 && alarmstring != _AlarmResource_NoAlarm) {
			var sssid = record.get("sssid");
			var trackername = record.get("trackername");
			//var alarmexpression = record.get("qtipalarm") + ' ' + record.get("lastalarmtime");
			var updatetime = record.get("lastupdate");
			var alarmtime = record.get("lastalarmtime");
			var alarmspeed = record.get("alarmspeed");
			var alarmlatitude = record.get("alarmlatitude");
			var alarmlongitude = record.get("alarmlongitude");
			var alarmexp = record.get("alarmexp");
			//var lati = record.get("latitude");
			//var longi = record.get("longitude");
			if (record.get("actionalarm") == "icon-alarm" && (!isInputAlarm(alarmexp))) {
				addAlarmtoImmAlarmList(sssid, trackername, alarmtime, alarmlatitude, alarmlongitude, alarmexp, record.get("alarmtime"), alarmspeed, false);
				if (isOpenExtentFn)
					lightButton.setDisabled(false);
			}
		}
	}
	setTimeout(function () {
		if (showtrackeronlinestatus) {
			onlinestore.load({
				callback : function () {
					onlinestore.each(function (record) {
						var sssid = record.get("sssid");
						var devicecount = devicestore.getCount();
						for (i = 0; i < devicecount; i++) {
							var drecord = devicestore.getAt(i);
							var tmpid = drecord.get("sssid");
							if (tmpid == sssid) {
								drecord.set("online", record.data['online']);
							}
						}
					})
				}
			});
		}
	}, 1000);
});

var cbutRetry = new Ext.ux.grid.CellActions({
		iconIndex : 'actionretry',
		qtipIndex : 'qtipretry'
	});

var cbutAlarm = new Ext.ux.grid.CellActions({
		iconIndex : 'actionalarm',
		qtipIndex : 'qtipalarm',
		height : 160
	});

function renderOnline(value, metaData, record, rowIndex, colIndex, store) {
	if (value)
		return '<img style="width:16px;height:16px;cursor: pointer;" ext:qtip="' + _TrackerMain_Online + '" src="images/greenblock.jpg"   />';
	else
		return '<img style="width:16px;height:16px;cursor: pointer;" ext:qtip="' + _TrackerMain_Offline + '" src="images/yellowBlock.jpg"  />';
}

function renderRoute(value, metaData, record, rowIndex, colIndex, store) {
	if (value)
		return '<img style="width:16px;height:16px;cursor:pointer;" onclick="editRouteEvent(\'' + record.data.sssid + '\',\'' + value + '\',\'' + record.get('routename') + '\',' + record.get('distance') + ')" ext:qtip="' + _RouteResources_EditRoute + '" src="images/er.png" />&nbsp;&nbsp;<img  style="width:16px;height:16px;cursor:pointer;" onclick="deleteDefinedRoute(\'' + record.data.sssid + '\',' + rowIndex + ')" ext:qtip="' + _RouteResources_DeleteRoute + '" src="images/dr.png" />';
	else
		return "";
}

function statusIconOnclick(bitindex, trackername) {
	var inputindex = bitindex - 8; //input4 index is 3
	inputStatusWindow(true, bitindex, trackername);
}

function renderStatus(value, metaData, record, rowIndex, colIndex, store) {
	if (value.length) {
		if (value.length > 0) {
			var html = '';
			var i = 0;
			for (i = 0; i < showStatuseInfoArray.length; i++) {
				var sinfoclass = showStatuseInfoArray[i];
				var bitstatus = getDefinedStatus(value, sinfoclass.bitIndex);
				var trueexp = sinfoclass.TrueExp;
				var falseexp = sinfoclass.FalseExp;
				var icontrue = sinfoclass.iconTrue;
				var iconfalse = sinfoclass.iconFalse;
				var sssid = record.get('sssid');
				if (g_DicTrackerStateDefine.ContainsKey(sssid)) {
					if (g_DicTrackerStateDefine.Item(sssid).ContainsKey(sinfoclass.bitIndex)) {
						var record = g_DicTrackerStateDefine.Item(sssid).Item(sinfoclass.bitIndex);
						trueexp = record.get('true_exp');
						falseexp = record.get('false_exp');
						//icontrue = record.get('true_icon');
						//iconfalse = record.get('false_icon');
					}
				};
				if (bitstatus)
					html += '<img style="width:16px;height:16px;cursor:pointer;" ext:qtip="' + trueexp + '" src="images/' + icontrue + '" onclick="javascript:statusIconOnclick(' + sinfoclass.bitIndex + ',\'' + record.get("trackername") + '\')" />';
				else
					html += '<img style="width:16px;height:16px;cursor:pointer;" ext:qtip="' + falseexp + '" src="images/' + iconfalse + '" onclick="javascript:statusIconOnclick(' + sinfoclass.bitIndex + ',\'' + record.get("trackername") + '\')" />';

			}
			return html;
		} else
			return "";
	} else
		return "";
}

function getDefinedStatus(statusstr, bitIndex) {
	var BinStr = padLeft(parseInt(statusstr, 16).toString(2), '0', 16);
	var bitStr = BinStr.substr(16 - bitIndex - 1, 1);
	return bitStr == "1" ? true : false;
}

var cols = [];

if (showtrackeronlinestatus) {
	cols.push({
		id : 'colonline',
		header : "",
		width : 28,
		sortable : false,
		dataIndex : 'online',
		renderer : renderOnline
	});
}
if (showStatuseInfoArray.length > 0) {
	cols.push({
		id : 'colstatus',
		header : "",
		width : 20 * showStatuseInfoArray.length,
		sortable : false,
		dataIndex : 'status',
		renderer : renderStatus
	});
}
cols.push({
	id : 'colalarm',
	header : "",
	width : 25,
	sortable : false,
	dataIndex : 'alarminfo',
	cellActions : [cbutAlarm]
});
cols.push(chkDeviceSelection);
if (showroutemodel) {
	cols.push({
		header : _RouteResources_DefineRouteAction,
		dataIndex : 'routedata',
		renderer : renderRoute
	});
}
cols.push({
	header : _TrackerMain_TrackerName,
	width : 100,
	dataIndex : 'trackername'
});
cols.push({
	header : _TrackerMain_LastUpdate,
	width : 120,
	dataIndex : 'lastupdate',
	renderer : function (value) {
		if (value == null)
			return "";
		var tmp = value.split('-');
		if (tmp.length >= 3) {
			//if has year, don't display year for it tool long
			var pos1 = value.indexOf('-');
			return value.substr(pos1 + 1, value.length - pos1 - 1);
		} else
			return value;
	}
});
if (isOpenExtentFn) {
	cols.push({
		header : _TrackerMain_ServiceDue,
		width : 70,
		dataIndex : 'servicedue'
	});
}
cols.push({
	header : _TrackerMain_Process,
	width : 100,
	dataIndex : 'process'
});
//cols.push({ header: _TrackerMain_Retry, width: 45, dataIndex: 'retry', cellActions: [cbutRetry] });
cols.push({
	header : _TrackerMain_UserName,
	dataIndex : 'username',
	width : 0,
	hidden : true
});
var coldeviceModel = new Ext.grid.ColumnModel({
		//    columns:[
		//    //{header: 'sssid',width: 80, dataIndex: 'sssid'},
		//        {id: 'colalarm', header: "", width: 25, sortable: false, dataIndex: 'alarminfo', cellActions: [cbutAlarm] }
		//       ,
		//         chkDeviceSelection,
		//        {header: _TrackerMain_TrackerName, dataIndex: 'trackername'},
		//        {header: _TrackerMain_LastUpdate,width: 80, dataIndex: 'lastupdate'},
		//        {header: _TrackerMain_Process, width:130,dataIndex: 'process'},
		//        {header: _TrackerMain_Retry, width: 35,dataIndex: 'retry',cellActions:[cbutRetry]},
		//        {header: _TrackerMain_UserName,dataIndex: 'username',width:0,hidden:true}
		//    ],
		columns : cols,
		defaults : {
			sortable : true,
			menuDisabled : true,
			width : 75
		}
	});

var grdviewgroup = new Ext.grid.GroupingView({
		startCollapsed : deviceListCollapsed,
		//forceFit:true,
		groupTextTpl : '{gvalue} ({[values.rs.length]} {[values.rs.length > 1 ? _TrackerMain_Devices : _TrackerMain_Device]})'
	});

DeviceList.Grid = Ext.extend(Ext.grid.GridPanel, {
		initComponent : function () {
			this.cellActions = new Ext.ux.grid.CellActions({
					listeners : {
						action : function (grid, record, action, value) {
							if (action == 'icon-alarm') {
								submitAndCancelAlarm(record.get("sssid"));
							} else if (action == 'icon-resend') {
								addSingleTCPCommand(record);
							}
						}
					},
					callbacks : {
						'icon-undo' : function (grid, record, action, value) {
							// Ext.ux.Toast.msg('Callback: icon-undo', 'You have clicked: <b>{0}</b>, action: <b>{1}</b>', value, action);
						}
					},
					align : 'left'

					//            ,renderer : function (data, metadata, record, rowIndex, columnIndex, store) {
					//                var qtip = '>';
					//                if(data >= 0){
					//                    qtip = " qtip='yeah'/>";
					//                    return '<span style="color:green;"' + qtip + data + '%</span>';
					//                }else if(data < 0){
					//                    qtip = " qtip='woops'/>";
					//                    return '<span style="color:red;"' + qtip + data + '%</span>';
					//                }
					//                return data;
					//            }
				});

			Ext.apply(this, {
				//store: devicestore,
				colModel : coldeviceModel,
				plugins : [this.cellActions, chkDeviceSelection],
				view : grdviewgroup,
				viewConfig : {
					forceFit : true
				},
				stripeRows : true,
				loadMask : true,
				listeners : {
					load : {
						scope : this,
						fn : function () {
							this.getSelectionModel().selectFirstRow();
						}
					}
				}
			});
			DeviceList.Grid.superclass.initComponent.apply(this, arguments);
		} //end function initComponent
	,
		onRender : function () {
			DeviceList.Grid.superclass.onRender.apply(this, arguments);

		} // eo function onRender
	});

// register component
Ext.reg('devicelistgrid', DeviceList.Grid);

var txtSearchDeviceKey = new Ext.form.TextField({
		allowBlank : true,
		maxLength : 32,
		emptyText : _TrackerMain_Search,
		maxText : _Message_MaxText + ' 32'	,
		listeners: {
			render: function(f){
					f.el.on('keyup', function(e){
							if(e.keyCode == 13){
								searchTracker();
							}
					});
			}
		}
	});

var devtoolbaritems = [
					txtSearchDeviceKey,
					{
						tooltip : {
							text : _TrackerMain_Search,
							autoHide : true
						},
						icon : 'Content/images/search16.gif',
						handler : function () {
							searchTracker();
							// devicestore.each(function (record) {
								// record.set("choosed", false);
							// });

							// devicestore.each(function (record) {
								// var tname = record.get("trackername");
								// if (tname.indexOf(k) != -1)
									// record.set("choosed", true);
							// });
							// if (imap != null) {
								// imap._bolfirsttimeload = true;
								// getAndDrawLastLocation(true, true);
							// }
						}
					}, {
						tooltip : {
							text : _TrackerMain_SelectAll,
							autoHide : true
						},
						iconCls : 'icon-selectall',
						handler : selectAll,
						scope : this
					}, {
						tooltip : {
							text : _TrackerMain_SelectNone,
							autoHide : true
						},
						iconCls : 'icon-selectnone',
						handler : selectNone,
						scope : this
				},
				   {
					   tooltip: { text: _Title_Reload, autoHide: true },
					   iconCls: 'icon-loadselection',
					   handler: function(){ grddevice.getStore().reload();},
					   scope: this
				   }
			   /* phu comment
			   {
				   tooltip: { text: _TrackerMain_LoadSelection, autoHide: true },
				   iconCls: 'icon-loadselection',
				   handler: loadSelection,
				   scope: this
			   },
				{
					tooltip : {
						text : _TrackerMain_RealTime,
						autoHide : true
					},
					iconCls : 'icon-userrtt',
					handler : userRTT,
					scope : this
				}
				*/
];

if (showroutemodel) {
	devtoolbaritems.push({
		tooltip : {
			text : _RouteResources_DrawRoute,
			autoHide : true
		},
		iconCls : 'icon-route-add',
		handler : function () {
			if (imap._isEditMode == false) {
				Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
				Ext.Msg.show({
					title : _TrackerMain_Title,
					msg : _RouteResources_StartDrawMessage,
					buttons : Ext.Msg.OK,
					animEl : 'elId',
					icon : Ext.MessageBox.INFO
				});
				imap.drawRouteLine();
			} else {
				Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
				Ext.Msg.show({
					title : _TrackerMain_Title,
					msg : _RouteResources_IsEdited,
					buttons : Ext.Msg.OK,
					animEl : 'elId',
					icon : Ext.MessageBox.INFO
				});
			}

		}
	});
	devtoolbaritems.push({
		tooltip : {
			text : _RouteResources_GoPrevious,
			autoHide : true
		},
		iconCls : 'icon-route-prev',
		disabled : true,
		handler : function () {
			imap.goPrevDefinedRouteStep(this);
		}
	});
	devtoolbaritems.push({
		tooltip : {
			text : _RouteResources_GoNext,
			autoHide : true
		},
		iconCls : 'icon-route-next',
		disabled : true,
		handler : function () {
			imap.goNextDefinedRouteStep(this);
		}
	});
}

var lightButton = new Ext.Toolbar.Button({
		tooltip : {
			text : _TrackerMain_CompleteAllAlarm,
			autoHide : true
		},
		iconCls : 'icon-light',
		disabled : true,
		handler : function () {
			submitAndCancelAlarm("", true);
		}
	});

if (isOpenExtentFn) {
	devtoolbaritems.push(lightButton);
}

var devtoolbar = new Ext.Toolbar({
		items : devtoolbaritems
	});

// Select all divice in list
function selectAll() {
	devicestore.each(function (record) {
		record.set("choosed", true);
	});
	if (imap != null) {
		imap._bolfirsttimeload = true;
		//getAndDrawLastLocation(true, true);
		addAllDeviceToMap();
		console.log('aaaa');
	}
}

function selectNone() {
	devicestore.each(function (record) {
		record.set("choosed", false);
		//imap.removeFromMap(record.get('sssid'));
	});
}

function saveSelectionToCookie(cookiename) {
	var sssids = "";
	var count = devicestore.getCount();
	var i;
	for (i = 0; i < count; i++) {
		if (devicestore.getAt(i).get("choosed"))
			sssids += sssids.length > 0 ? "|" + devicestore.getAt(i).get("sssid") : devicestore.getAt(i).get("sssid");
	}

	deleteCookie(cookiename);
	setCookie(cookiename, sssids, 365);
}

function saveSelection() {

	Ext.MessageBox.buttonText.ok = _TrackerMain_Save;
	Ext.MessageBox.buttonText.cancel = _TrackerMain_Cancel;
	Ext.MessageBox.prompt(_TrackerMain_SaveSelection, _Message_SaveSelectionCaption, function (btn, text) {
		if (btn == 'ok' && text.length > 0) {
			saveSelectionToCookie(text);
		}
	});
}

function loadSelection() {
	Ext.MessageBox.buttonText.ok = _TrackerMain_Load;
	Ext.MessageBox.buttonText.cancel = _TrackerMain_Cancel;
	Ext.MessageBox.prompt(_TrackerMain_LoadSelection, _Message_LoadSelectionCaption, function (btn, text) {
		if (btn == 'ok' && text.length > 0) {
			loadSelectionFromCookie(text);
			if (onlyshowselecteddevice) {
				if (imap != null) {
					imap._bolfirsttimeload = true;
					getAndDrawLastLocation(true, true);
				}
			}
		}
	});
}

function loadSelectionFromCookie(cookiename) {
	var sssids = getCookie(cookiename);
	if (sssids != null) {
		var sssid = sssids.split('|');
		var i;
		devicestore.each(function (record) {
			record.set("choosed", false);
		});
		for (i = 0; i < sssid.length; i++) {
			devicestore.each(function (record) {
				if (record.get("sssid") == sssid[i])
					record.set("choosed", true);
			});
		}
	} else {
		Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
		Ext.Msg.show({
			title : _TrackerMain_Title,
			msg : _Message_NoSelection,
			buttons : Ext.Msg.OK,
			animEl : 'elId',
			icon : Ext.MessageBox.WARNING
		});
	}
}

var rtrakingWindows = []; //traking map panel
var nextwindowx = 30;
var nextwindowy = 30;

function createNewTrackingWindow(sssid, trackername, windowx, windowy) {
	if (meimaptype == 0) {
		var tmpwin = new Ext.ux.GMapWindow({
				title : _TrackerMain_RealTimeTracking + "(" + trackername + ")",
				closable : true,
				width : 500,
				height : 450,
				minimizable : false,
				plain : true,
				x : windowx,
				y : windowy
			});
		tmpwin.deviceID = sssid;

		return tmpwin;
	} else if (meimaptype == 1) {
		var tmpwin = new Ext.ux.BMapWindow({
				title : _TrackerMain_RealTimeTracking + "(" + trackername + ")",
				closable : true,
				width : 500,
				height : 450,
				minimizable : false,
				plain : true,
				x : windowx,
				y : windowy
			});
		tmpwin.deviceID = sssid;

		return tmpwin;
	} else if (meimaptype == 2) {
		var tmpwin = new Ext.ux.MMapWindow({
				title : _TrackerMain_RealTimeTracking + "(" + trackername + ")",
				closable : true,
				width : 500,
				height : 450,
				minimizable : false,
				plain : true,
				x : windowx,
				y : windowy
			});
		tmpwin.deviceID = sssid;

		return tmpwin;
	} else if (meimaptype == 3) {
		var tmpwin = new Ext.ux.GMapWindow({
				title : _TrackerMain_RealTimeTracking + "(" + trackername + ")",
				closable : true,
				width : 500,
				height : 450,
				minimizable : false,
				plain : true,
				x : windowx,
				y : windowy
			});
		tmpwin.deviceID = sssid;

		return tmpwin;
	} else if (meimaptype == 4) {
		var tmpwin = new Ext.ux.QMapWindow({
				title : _TrackerMain_RealTimeTracking + "(" + trackername + ")",
				closable : true,
				width : 500,
				height : 450,
				minimizable : false,
				plain : true,
				x : windowx,
				y : windowy
			});
		tmpwin.deviceID = sssid;

		return tmpwin;
	}
}

function deleteDefinedRoute(sssid, rowIndex) {
	Ext.MessageBox.YESNO = {
		yes : _TrackerMain_Yes,
		no : _TrackerMain_No
	};
	Ext.MessageBox.confirm(_TrackerMain_Title, _RouteResources_SureToDelete, function (btn) {
		if (btn == "no") {}
		if (btn == "yes") {

			if (sssid.length != "") {
				Ext.Ajax.request({
					url : 'HandlerDefinedRoute',
					success : function (response, opts) {
						var obj = Ext.decode(response.responseText);
						if (obj.success == true) {
							Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
							Ext.Msg.show({
								title : _TrackerMain_Title,
								msg : _RouteResources_Successful,
								buttons : Ext.Msg.OK,
								animEl : 'elId',
								icon : Ext.MessageBox.INFO
							});
							grddevice.getStore().getAt(rowIndex).set("routedata", "");
							imap.clearRoute();
						} else {
							Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
							Ext.Msg.show({
								title : _TrackerMain_Title,
								msg : _RouteResources_Failed,
								buttons : Ext.Msg.OK,
								animEl : 'elId',
								icon : Ext.MessageBox.INFO
							});
						}

					},
					failure : function () {
						Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
						Ext.Msg.show({
							title : _TrackerMain_Title,
							msg : _POI_AddFailed,
							buttons : Ext.Msg.OK,
							animEl : 'elId',
							icon : Ext.MessageBox.INFO
						});
					},
					timeout : 20000,
					params : {
						type : 'delete',
						snimeiid : sssid
					}
				});
			} else {
				Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
				Ext.Msg.show({
					title : _TrackerMain_Title,
					msg : _Message_MustChooseADevice,
					buttons : Ext.Msg.OK,
					animEl : 'elId',
					icon : Ext.MessageBox.WARNING
				});
			}
		}
	});
}

function cancelAddRouteEvent() {
	//imap.changeTool(EnumMapToolType.DrawDefinedRoute);
	imap.clearRoute();
}

function editRouteEvent(sssid, value, name, distance) {
	if (imap._isEditMode == false) {
		imap.showOneEditRoute(sssid, value, name, distance);
	} else {
		Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
		Ext.Msg.show({
			title : _TrackerMain_Title,
			msg : _RouteResources_IsEdited,
			buttons : Ext.Msg.OK,
			animEl : 'elId',
			icon : Ext.MessageBox.INFO
		});
	}

}

function submitAddRouteEvent(pointString, isEditAll, editid) {
	var recordStote = grddevice.getStore();
	var sssid = "";
	if (editid != "" && editid != undefined && editid != 'null')
		sssid = editid;
	for (var i = 0; i < recordStote.getCount(); i++) {
		if (recordStote.getAt(i).get("choosed") || isEditAll == true) {
			if (sssid == "")
				sssid = recordStote.getAt(i).get("sssid");
			else
				sssid += "," + recordStote.getAt(i).get("sssid");
		}
	}

	if (sssid.length != "") {
		var routeName = document.getElementById('my_route_line').value;
		var routeDistance = document.getElementById('my_route_line_distance').value;
		if (isNaN(routeDistance)) {
			Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
			Ext.Msg.show({
				title : _TrackerMain_Title,
				msg : _CustomerConfigResource_NumberValid,
				buttons : Ext.Msg.OK,
				animEl : 'elId',
				icon : Ext.MessageBox.INFO
			});
			return;
		}
		//        var radios = document.getElementsByName('far_or_close_route');
		//        var atype = radios[0].checked ? radios[0].value : radios[1].value;
		Ext.Ajax.request({
			url : 'HandlerDefinedRoute',
			success : function (response, opts) {
				var obj = Ext.decode(response.responseText);
				if (obj.success == true) {
					Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
					Ext.Msg.show({
						title : _TrackerMain_Title,
						msg : _RouteResources_Successful,
						buttons : Ext.Msg.OK,
						animEl : 'elId',
						icon : Ext.MessageBox.INFO
					});
					imap.clearRoute();
					recordStote.reload();
				} else {
					Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
					Ext.Msg.show({
						title : _TrackerMain_Title,
						msg : _RouteResources_Failed,
						buttons : Ext.Msg.OK,
						animEl : 'elId',
						icon : Ext.MessageBox.INFO
					});
				}

			},
			failure : function () {
				Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
				Ext.Msg.show({
					title : _TrackerMain_Title,
					msg : _POI_AddFailed,
					buttons : Ext.Msg.OK,
					animEl : 'elId',
					icon : Ext.MessageBox.INFO
				});
			},
			timeout : 20000,
			params : {
				type : 'add',
				snimeiid : sssid,
				pointsString : pointString,
				atype : 0,
				routeName : routeName,
				routeDistance : routeDistance
			}
		});
	} else {
		Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
		Ext.Msg.show({
			title : _TrackerMain_Title,
			msg : _Message_MustChooseADevice,
			buttons : Ext.Msg.OK,
			animEl : 'elId',
			icon : Ext.MessageBox.WARNING
		});
	}
}

function setServiceDue() {
	if (grddevice.getSelectionModel().getCount() > 0) {
		var record = grddevice.getSelectionModel().getSelected();
		var sssid = record.get("sssid");
		var journey = record.get("journey") / 1000;
		var servicedue = record.get("servicedue");

		var win = serviceDueWindow(sssid, record.get("trackername"), journey, servicedue);
		nextwindowx += 20;
		nextwindowy += 20;
		win.show(); // 显示出来
	} else {
		Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
		Ext.Msg.show({
			title : _TrackerMain_Title,
			msg : _Message_MustChooseADevice,
			buttons : Ext.Msg.OK,
			animEl : 'elId',
			icon : Ext.MessageBox.WARNING
		});
	}
}

function userRTT() {
	if (grddevice.getSelectionModel().getCount() > 0) {
		var record = grddevice.getSelectionModel().getSelected();
		var sssid = record.get("sssid");
		var alreadyHasDeviceWindow = false;
		var i;
		for (i = 0; i < rtrakingWindows.length; i++) {
			if (rtrakingWindows[i].deviceID == sssid) {
				alreadyHasDeviceWindow = true;
				break;
			}
		}
		if (!alreadyHasDeviceWindow) {
			var win = createNewTrackingWindow(sssid, record.get("trackername"), nextwindowx, nextwindowy);
			nextwindowx += 20;
			nextwindowy += 20;
			win.show(); // 显示出来
			win.addListener('beforeclose', function (p) {
				if (rtrakingWindows.indexOf(p) != -1) {
					rtrakingWindows.remove(p);
				}
			});
			var rmap = createMap(win.getMap(), true, null, gmapurl); //new MSGMap(win.getMap(), true, null, gmapurl);
			win.MapObject = rmap;
			rtrakingWindows.push(win);

			var singlelocationstore = createSingleLocationStore(sssid);
			singlelocationstore.load({
				callback : function () {
					var count = singlelocationstore.getCount();
					if (count > 0) {
						if (rmap) {
							var record = singlelocationstore.getAt(0);
							rmap.setCenterbyLatLng(record.get("latitude"), record.get("longitude"), 14);
						}
					} else {
						//has no location yet
						rmap.setCenterbyLatLng(0, 0, 14);

					}
				}
			});

		} else {
			Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
			Ext.Msg.show({
				title : _TrackerMain_Title,
				msg : _Message_AlreadyHasThisDeviceRTTWindow,
				buttons : Ext.Msg.OK,
				animEl : 'elId',
				icon : Ext.MessageBox.INFO
			});
		}
	} else {
		Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
		Ext.Msg.show({
			title : _TrackerMain_Title,
			msg : _Message_MustChooseADevice,
			buttons : Ext.Msg.OK,
			animEl : 'elId',
			icon : Ext.MessageBox.WARNING
		});
	}
}

var grddevice = new DeviceList.Grid({
		store : devicestore,
		autoWidth : true,
		height : 80,
		autoScroll : true,
		filter: true
		//,tbar:devtoolbar
	});

grddevice.addListener('render', function (grid) {
	var store = grid.getStore(); // Capture the Store.
	var view = grid.getView(); // Capture the GridView.
	grid.tip = new Ext.ToolTip({
			target : view.mainBody, // The overall target element.
			//delegate: '.x-grid3-row', // Each grid row causes its own seperate show and hide.
			delegate : '.x-grid3-cell', // Each grid cell causes its own seperate show and hide.
			trackMouse : true, // Moving within the row should not hide the tip.
			renderTo : document.body, // Render immediately so that tip.body can be referenced prior to the first show.
			listeners : { // Change content dynamically depending on which element triggered the show.
				beforeshow : function updateTipBody(tip) {
					var rowIndex = view.findRowIndex(tip.triggerElement);
					var cellIndex = view.findCellIndex(tip.triggerElement);
					var addinColumn = showtrackeronlinestatus ? 1 : 0;
					addinColumn += showStatuseInfoArray.length > 0 ? 1 : 0;
					//addinColumn += showroutemodel ? 1 : 0;
					addinColumn += isOpenExtentFn ? 1 : 0;
					if (cellIndex == addinColumn) {
						if (rowIndex == 0 || rowIndex != false) {
							var strAlarm = store.data.items[rowIndex].get('qtipalarm');
							var tmp = strAlarm.split('|');
							if (tmp.length > 0) {
								var atype = getAlarmTypeFromAlarmString(tmp[0]);
								if (atype == EnumAlarmType.SOSButton_Pressed_Input1_Active || atype == EnumAlarmType.ButtonB_Pressed_Input2_Active || atype == EnumAlarmType.ButtonC_Pressed_Input3_Active || atype == EnumAlarmType.Input4_Active || atype == EnumAlarmType.Input5_Active
									 || atype == EnumAlarmType.SOSButton_Released_Input1_InActive || atype == EnumAlarmType.ButtonB_Released_Input2_InActive || atype == EnumAlarmType.ButtonC_Released_Input3_InActive || atype == EnumAlarmType.Input4_InActive || atype == EnumAlarmType.Input5_InActive) {
									var alarm = getAlarmStringFromAlarmType(atype); //transto user defined alarm
									if (tmp.length > 1)
										tip.body.dom.innerHTML = alarm + " " + tmp[1];
									else
										tip.body.dom.innerHTML = alarm;
								} else {
									if (tmp.length > 1) {
										tip.body.dom.innerHTML = tmp[0] + " " + tmp[1];
									} else
										tip.body.dom.innerHTML = tmp[0];
								}

							} else {
								tip.body.dom.innerHTML = strAlarm;
							}

						}
					} else if (cellIndex == 3 + addinColumn || cellIndex == 4 + addinColumn) {
						var cell = view.getCell(rowIndex, cellIndex);
						if (cell.innerHTML.length > 1) {
							tip.body.dom.innerHTML = cell.innerHTML;
							return true;
						} else
							return false;
					} else {
						return false;
					}
				}
			}
		});
});

//if (onlyshowselecteddevice) {
//    grddevice.addListener('cellclick', function(grd, rowIndex, columnIndex, e) {
//        if (columnIndex == 1) {
//
//        }
//    });
//}
// phu moi add cai nay
//onlyshowselecteddevice = true;

if (onlyshowselecteddevice) {
	grddevice.addListener('afteredit', function (grd, record) {
		if (imap != null) {
			var ids = record.get('sssid');
			var choosed = record.get('choosed');
			if (choosed) {
				imap._bolfirsttimeload = true;
				getAndDrawLastLocation(true, true);				
				imap.addTrackerMarker(ids);
			} else{
				imap.removeFromMap(ids);
			}
		}
	});
}

function createSingleLocationStore(sssid) {
	var singlelocationreader = new Ext.data.JsonReader({}, locationfields);
	var singlelocationproxy = new Ext.data.HttpProxy({
			url : 'HandlerSingleLastLocation?sssid=' + sssid
		});

	var singlelocationstore = new Ext.data.Store({
			reader : singlelocationreader,
			proxy : singlelocationproxy
		});

	return singlelocationstore;
}

grddevice.addListener('rowdblclick', function (grid, rowindex, e) {
	var sssid = devicestore.getAt(rowindex).get("sssid");
	imap.panToDevice(sssid);

	var sssid = devicestore.getAt(rowindex).get("sssid");
	myChooseDeviceListRowSSSID = sssid;
	var singlelocationstore = createSingleLocationStore(sssid);
	singlelocationstore.load({
		callback : function (r, options, success) {
			if (success) {
				if (showmiles) {
					singlelocationstore.each(function (record) {
						record.set('speed', kilos2miles(record.get('speed')));
					});
				}
				if (imap != null) {
					var count = singlelocationstore.getCount();
					if (count > 0) {
						//imap.drawFromStore(singlelocationstore, true);
						singlelocationstore.each(function (record) {
							showStatusinPanelByRecord(record);
							devicestore.getAt(rowindex).set("lastupdate", record.get("receivedtime"));
						});
					} else {
						Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
						Ext.Msg.show({
							title : _TrackerMain_Title,
							msg : _Message_TrackerNoData,
							buttons : Ext.Msg.OK,
							animEl : 'elId',
							icon : Ext.MessageBox.INFO
						});
					}
				}
			} else {
				Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
				Ext.Msg.show({
					title : _TrackerMain_Title,
					msg : _TAResources_Failure,
					buttons : Ext.Msg.OK,
					animEl : 'elId',
					icon : Ext.MessageBox.INFO
				});
			}
		}
	});

});

grddevice.addListener("rowcontextmenu", function (grid, rowIndex, e) {
	e.preventDefault();
	grid.getSelectionModel().selectRow(rowIndex);
	if (rowIndex < 0) {
		return;
	}
	var treeMenu = new Ext.menu.Menu({
			items : [{
					xtype : "menuitem",
					text : _TrackerMain_RealTime,
					icon : "images/track216.gif",
					pressed : true,
					handler : function () {
						userRTT()
					}
				}

				/*,{ xtype: "menuitem", text: _CommandExpression_GetLastPicture, pressed: true, handler: function() {
				sendGetPictureCommand();
				}
				},
				{ xtype: "menuitem", text: _TrackerMain_ShowImage, pressed: true, handler: function() {
				showPicture();
				}
				}*/
			]
		});
	treeMenu.showAt(e.getPoint());
	if (isOpenExtentFn) {
		treeMenu.addItem(new Ext.menu.Item({
				xtype : "menuitem",
				text : _TrackerMain_SetServiceDue,
				pressed : true,
				handler : function () {
					setServiceDue();
				}
			}));
	}
});

function submitAndCancelAlarm(sssid, cancelAll) {
	if (cancelAll == true) {
		var sssids = "";
		var records = new Array();
		var count = devicestore.getCount();
		for (var j = 0; j < count; j++) {
			var record = devicestore.getAt(j);
			var myId = record.get('sssid');
			var actionalarm = record.get('actionalarm');
			if (actionalarm != "icon-none") {
				records.push(record);
				if (sssids == "") {
					sssids = myId;
				} else {
					sssids += "," + myId;
				}
			}
		}
		Ext.Ajax.request({
			url : 'HandlerCompleteAlarms',
			method : 'post',
			params : {
				sssids : sssids
			},
			success : function (back) {
				var val = back.responseText;
				lightButton.setDisabled(true);
				if (val == 1) {
					for (var i = 0; i < records.length; i++) {
						records[i].set("actionalarm", "icon-none");
						records[i].set("qtipalarm", "");
						submitAndCancelAlarm(records[i].get('sssid'));
						//                        var singlelocationstore = createSingleLocationStore(records[i].get('sssid'));
						//                        singlelocationstore.load({
						//                            callback: function() {
						//                                if (imap != null) {
						//                                    var count = singlelocationstore.getCount();
						//                                    if (count > 0) {
						//                                        imap.drawFromStore(singlelocationstore, false);
						//                                    }

						//                                }
						//                            }
						//                        });
					}
					devicestore.reload();
				}
			}
		});
	} else {
		Ext.Ajax.request({
			url : 'HandlerCompleteAlarm',
			method : 'post',
			params : {
				sssid : sssid
			},
			success : function (back) {
				var val = back.responseText;
				if (val == 1) {
					var rowindex = devicestore.find("sssid", sssid);
					var record = devicestore.getAt(rowindex);
					record.set("actionalarm", "icon-none");
					record.set("qtipalarm", "");
					var singlelocationstore = createSingleLocationStore(sssid);
					singlelocationstore.load({
						callback : function () {

							if (showmiles) {
								singlelocationstore.each(function (record) {
									record.set('speed', kilos2miles(record.get('speed')));
								});
							}
							if (imap != null) {
								var count = singlelocationstore.getCount();
								if (count > 0) {
									//imap.drawFromStore(singlelocationstore, false);
								}

							}
						}
					});
				}
			}
		});
	}
}

/******************2010-8-18******by winston*******/
function getHasEmergencyStatus() {
	var hasEmergency = false;
	devicestore.each(function (record) {
		var a = record.get("actionalarm");
		if (a == 'icon-alarm') {
			hasEmergency = true;
		}
	});
	return hasEmergency;
}
/*****************************************/
// Check box change listener
grddevice.addListener('afteredit', function (grd, record) {
	var ids = record.get('sssid');
	var choosed = record.get('choosed');
	if (choosed) {
		imap._bolfirsttimeload = true;
		getAndDrawLastLocation(true, true);
		
		
		//Call ajax to get infomation and add marker to map
		Ext.Ajax.request({
			url : 'HandlerLastLocation?DeviceKeySecurity='+ids,
			success : function (response, opts) {
				var obj = Ext.decode(response.responseText);				
				var trackerinfo = new TrackerInfo(obj[0]);
				imap.addTrackerMarker(trackerinfo);
			}
		});
	} else{
		imap.removeTrackerMarker(ids);
	}
});
// Grid filter
function searchTracker(){
	var trackerName = txtSearchDeviceKey.getValue();
	grddevice.store.clearFilter();
	if (trackerName) {
		var matcher = new RegExp(Ext.escapeRe(trackerName), "i");
		grddevice.getStore().filter('trackername', matcher);
	}
}

//Add all device to map
function addAllDeviceToMap(){
	Ext.Ajax.request({
		url : 'HandlerLastLocation',
		success : function (response, opts) {
			var lstDevice = Ext.decode(response.responseText);
			if(lstDevice != null){
				var lstInfo = [];
				
				for(var i = 0, len= lstDevice.length; i<len; i++){
					var trackerinfo = new TrackerInfo(lstDevice[i]);
					lstInfo.push(trackerinfo);
				}
				imap.addMultipTrackerMarker(lstInfo);
			}

		}
	});
};
TrackerItem = function(id, longitude,latitude,marker, iconname,direction){
	this.id = id;
	this.lng = longitude;
	this.lat = latitude;
	this.marker = marker;
	this.iconname = iconname;
	this.direction = direction;
};